#!/usr/bin/python
#coding:utf-8
'''
百度请求接口
'''
import urllib,requests,json,os,time
import base64Util 
import sys
import ssl
import fileTool as tool

access_token=""


checkUrl="https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="+access_token  #两张图片对比
detailUrl="https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token="+access_token  #图片详细信息

def getAccToken():
    '''
        重置参数access_token
    '''
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=&client_secret='
    response =urllib.request.urlopen(host)
    content = response.read()
    global access_token
    if content:
        reqText=json.loads(content)
        access_token=reqText['access_token']
        return True

    
    print("获取token异常")
    return False

def faceImgBase64(image):
    '''
    百度人脸图片分析接口
    args:
        image:图片地址
    
    return:
        请求结果
    '''
    # getAccToken()
    image=base64Util.fileToBase64(image)
    header = {'Content-Type': 'application/json'}
    data = "{\"image\":\""+image+"\",\"image_type\":\"BASE64\",\"face_field\":\"faceshape,facetype\"}"
    # response =requests.post(detailUrl,headers=header,data=data)
    # return response.text
    return "测试"

def detailImg(image):
    '''
    人脸检测：
    #222203 无法解析人脸  100:无效的参数   	222209:face token不存在
    args:
        image:图片base64字符串
    
    return:
        value:是否有人脸，0 有，1没有
    '''
    # image=str(image,'utf-8')
    header = {'Content-Type': 'application/json'}
    # data = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"face_field\":\"faceshape,facetype\"}"
    data = "{\"image\":\""+image+"\",\"image_type\":\"BASE64\",\"face_field\":\"faceshape,facetype\"}"
    response =requests.post(detailUrl,headers=header,data=data)
    reqText=json.loads(response.text)  # 返回结果：
    print(reqText)
    if reqText['error_code'] == 0:  #请求成功
        if reqText['result']['face_num']>0: #人脸数大于等于1
            return 0
    return 1
    #{"error_code":0,"error_msg":"SUCCESS","log_id":1525356520189,"timestamp":1530152726,"cached":0,"result":{"face_num":1,"face_list":[{"face_token":"4f0ba11aa823c5acbc491a5083be4049","location":{"left":9.780975342,"top":35.24531174,"width":189,"height":203,"rotation":-1},"face_probability":1,"angle":{"yaw":-3.431904554,"pitch":-1.283947587,"roll":-2.242849827},"face_shape":{"type":"oval","probability":0.4135839641},"face_type":{"type":"human","probability":0.9991436601}}]}}


def dealErrorFile():
    '''
    获取指定目录下所有文件，请求百度，判断是否有人脸
    '''
    url="D:/python-space/2019/facetest/2019-12-30/error/"
    fileList=tool.foundFile(url,'jpg')
    
    title="文件名,结果(0 有人脸，1 无人脸)"
    dataList=[]
    for file in fileList:
        jgp64=base64Util.fileToBase64(file)
        result=detailImg(jgp64)
        row=os.path.basename(file)+","+str(result)

        dataList.append(row)
        break
    
    file="./check/2019-12-30/test.txt"
    tool.writeFile(dataList,file,title)

